from flask import request, jsonify, current_app
from app.api import bp
from app.models.knowledge_base import KnowledgeBase, Document  # 已更新导入
from app import db, logger
from app.utils.errors import ValidationError, NotFoundError, ServiceError
from app.utils.response import APIResponse
from app.utils.file_handler import process_file  # 如果需要的话，更新导入

@bp.route('/knowledge-base', methods=['GET'])
def get_knowledge_bases():
    """获取知识库列表"""
    try:
        knowledge_bases = KnowledgeBase.query.order_by(KnowledgeBase.created_at.desc()).all()
        
        return APIResponse.success(data={
            'items': [{
                'id': kb.id,
                'name': kb.name,
                'description': kb.description,
                'embedding_model': kb.embedding_model,
                'document_count': kb.documents.count(),
                'created_at': kb.created_at.isoformat(),
                'updated_at': kb.updated_at.isoformat()
            } for kb in knowledge_bases]
        })
    except Exception as e:
        logger.error(f"Error fetching knowledge bases: {str(e)}")
        raise ServiceError(str(e))

@bp.route('/knowledge-base', methods=['POST'])
def create_knowledge_base():
    """创建知识库"""
    try:
        data = request.get_json()
        if not data:
            raise ValidationError("No input data provided")
        
        logger.info(f"Creating knowledge base with data: {data}")  # 添加日志
        
        # 验证必填字段
        if not data.get('name'):
            raise ValidationError("Knowledge base name is required")
        
        # 创建知识库
        kb = KnowledgeBase(
            name=data['name'],
            description=data.get('description'),
            embedding_model=data.get('embedding_model', 'bge-large')
        )
        
        db.session.add(kb)
        db.session.commit()
        
        logger.info(f"Knowledge base created with id: {kb.id}")  # 添加日志
        return APIResponse.success(
            data={
                'id': kb.id,
                'name': kb.name,
                'description': kb.description,
                'embedding_model': kb.embedding_model,
                'created_at': kb.created_at.isoformat(),
                'updated_at': kb.updated_at.isoformat()
            },
            message="Knowledge base created successfully"
        )
    except ValidationError as e:
        logger.warning(f"Validation error: {str(e)}")  # 添加日志
        return APIResponse.validation_error(message=str(e))
    except Exception as e:
        logger.error(f"Error creating knowledge base: {str(e)}", exc_info=True)  # 添加错误日志
        db.session.rollback()
        return APIResponse.error(message=str(e))

@bp.route('/knowledge-base/<int:id>', methods=['GET'])
def get_knowledge_base(id):
    kb = KnowledgeBase.query.get(id)
    if not kb:
        raise NotFoundError(f"Knowledge base {id} not found")
    
    return APIResponse.success(data={
        'id': kb.id,
        'name': kb.name,
        'description': kb.description,
        'embedding_model': kb.embedding_model,
        'document_count': kb.documents.count(),
        'created_at': kb.created_at.isoformat(),
        'updated_at': kb.updated_at.isoformat()
    })

@bp.route('/knowledge-base/<int:id>', methods=['PUT'])
def update_knowledge_base(id):
    kb = KnowledgeBase.query.get_or_404(id)
    data = request.get_json()
    kb.name = data.get('name', kb.name)
    kb.description = data.get('description', kb.description)
    kb.embedding_model = data.get('embedding_model', kb.embedding_model)
    db.session.commit()
    return APIResponse.success(data={
        'id': kb.id,
        'name': kb.name,
        'description': kb.description,
        'embedding_model': kb.embedding_model,
        'document_count': kb.documents.count(),
        'created_at': kb.created_at.isoformat(),
        'updated_at': kb.updated_at.isoformat()
    })

@bp.route('/knowledge-base/<int:id>', methods=['DELETE'])
def delete_knowledge_base(id):
    kb = KnowledgeBase.query.get_or_404(id)
    db.session.delete(kb)
    db.session.commit()
    return '', 204

@bp.route('/knowledge-base/<int:id>/stats', methods=['GET'])
def get_knowledge_base_stats(id):
    """获取知识库统计信息"""
    try:
        kb = KnowledgeBase.query.get_or_404(id)
        
        stats = {
            'document_count': kb.documents.count(),
            'embedding_model': kb.embedding_model,
            'created_at': kb.created_at.isoformat(),
            'last_updated': kb.updated_at.isoformat()
        }
        
        return APIResponse.success(data=stats)
    except Exception as e:
        logger.error(f"Error fetching stats for knowledge base {id}: {str(e)}")
        raise ServiceError(str(e)) 